<template>
  <div class="users-container">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="订单详情id">
          <el-input
            v-model="searchForm.orderDetailId"
            placeholder="请输入订单详情id"
          />
        </el-form-item>
        <el-form-item label="用户id">
          <el-input v-model="searchForm.userId" placeholder="请输入用户id" />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            style="width: 150px;"
            clearable
          >
            <!-- 保持原有选项配置 -->
            <el-option
              v-for="item in orderStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch"
            >搜索</el-button
          >
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 订单详情表格 -->
    <el-table :data="tableData" style="width: 100%" border>
      <el-table-column prop="orderDetailId" label="订单详情ID" />
      <el-table-column prop="ordersId" label="订单ID" />
      <el-table-column prop="userId" label="用户id" />
      <el-table-column prop="commodityId" label="商品id" />
      <el-table-column prop="commodityTitle" label="商品标题" width="300" />
      <el-table-column label="商品图片">
        <template #default="{ row }">
          <el-avatar :src="row.coverImage" />
        </template>
      </el-table-column>
      <el-table-column prop="skuName" label="规格" />
      <el-table-column prop="skuValueName" label="参数" />
      <el-table-column prop="status" label="订单状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{
              orderStatusOptions.find((item) => item.value == row.status)?.label
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="receiverName" label="收货姓名" width="100" />
      <el-table-column prop="receiverPhone" label="手机号" width="150" />
      <el-table-column
        prop="receiverAddressDescription"
        label="收货地址"
        width="200"
      />
      <el-table-column prop="quantity" label="数量" />
      <el-table-column prop="totalPrice" label="总价格" />
      <el-table-column prop="createTime" label="创建时间" width="100" />
      <el-table-column prop="updateTime" label="更新时间" width="100" />
      <el-table-column label="操作" width="70" fixed="right">
        <template #default="{ row }">
          <el-button
            type="primary"
            :icon="Edit"
            circle
            @click="handleEdit(row)"
          />
          <!-- 暂时不需要删除订单详情 -->
          <!-- <el-button
            type="danger"
            :icon="Delete"
            circle
            @click="handleDelete(row.id)"
          /> -->
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current="pagination.current"
        v-model:size="pagination.size"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 新增/编辑订单详情对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form :model="orderDetailForm" label-width="100px">
        <el-form-item label="收货姓名">
          <el-input v-model="orderDetailForm.receiverName" />
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="orderDetailForm.receiverPhone" />
        </el-form-item>
        <el-form-item label="收货地址">
          <el-input v-model="orderDetailForm.receiverAddressDescription" />
        </el-form-item>
      </el-form>
      <!-- 新增状态选择 -->
      <el-form-item label="订单状态">
        <el-select v-model="orderDetailForm.status" placeholder="请选择状态">
          <el-option
            v-for="item in orderStatusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Search, Delete, Edit } from "@element-plus/icons-vue";
import {
  getOrderDetailService,
  updateOrderAddressService,
} from "@/api/orderDetail";

// 订单详情列表数据
const tableData = ref([{}]);

// 分页配置
const pagination = ref({
  current: 1,
  size: 10,
  total: 100,
});

// 搜索表单
const searchForm = ref({
  orderDetailId: "",
  userId: "",
  status: "",
  dateRange: [],
});

// 新增/编辑订单详情对话框
const dialogVisible = ref(false);
const dialogTitle = ref("编辑订单详情");
const orderDetailForm = ref({
  orderDetailId: "",
  receiverName: "",
  receiverPhone: "",
  receiverreceiverDescription: "",
});

/**
 * 订单状态选项
 * */
const orderStatusOptions = [
  // 订单支付状态（1.待付款、2.已付款、3.待发货、4.已发货、5.已完成、6.取消订单）
  { label: "待付款", value: "1" },
  { label: "已付款", value: "2" },
  { label: "待发货", value: "3" },
  { label: "已发货", value: "4" },
  { label: "已完成", value: "5" },
  { label: "已取消", value: "6" },
];

/**
 * 获取订单状态对应的标签类型
 * */
const getStatusType = (status) => {
  const statusMap = {
    1: "warning",
    2: "success",
    3: "primary",
    4: "success",
    5: "danger",
    6: "info",
  };
  return statusMap[status] || "";
};
// 处理分页变化
const handlePageChange = (val) => {
  pagination.value.current = val;
  fetchUsers();
};

// 处理每页显示数量变化
const handleSizeChange = (val) => {
  pagination.value.size = val;
  fetchUsers();
};

// 搜索订单详情
const handleSearch = () => {
  pagination.value.current = 1;
  fetchUsers();
};

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    id: "",
    username: "",
    nickname: "",
    phone: "",
    dateRange: [],
  };
  handleSearch();
};

// 打开新增订单详情对话框
const handleAdd = () => {
  dialogTitle.value = "新增订单详情";
  orderDetailForm.value = {
    id: "",
    username: "",
    nickname: "",
    phone: "",
    avatar: "",
    password: "",
  };
  dialogVisible.value = true;
};

// 打开编辑订单详情对话框
const handleEdit = (row) => {
  // 填充表单数据
  orderDetailForm.value.orderDetailId = row.orderDetailId;
  orderDetailForm.value.receiverName = row.receiverName;
  orderDetailForm.value.receiverPhone = row.receiverPhone;
  orderDetailForm.value.receiverAddressDescription =
    row.receiverAddressDescription;
  dialogTitle.value = "编辑订单详情";
  dialogVisible.value = true;
};

// 删除订单详情
const handleDelete = (id) => {
  ElMessageBox.confirm("确定要删除该订单详情吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      // 这里添加删除订单详情的接口调用
      ElMessage.success("删除成功");
      fetchUsers();
    })
    .catch(() => {});
};

// 提交表单
const submitForm = async () => {
  console.log(orderDetailForm.value);
  // 编辑订单详情的接口调用
  let result = await updateOrderAddressService(orderDetailForm.value);
  ElMessage.success(result.message);
  // 关闭对话框
  dialogVisible.value = false;
  fetchUsers();
};

/**
 * 获取订单详情列表
 */
const fetchUsers = async () => {
  const params = {
    orderDetailId: searchForm.value.orderDetailId,
    userId: searchForm.value.userId, // 注意：这里可能需要根据实际字段调整
    status: searchForm.value.status,
    startTime: searchForm.value.dateRange[0],
    endTime: searchForm.value.dateRange[1],

    current: pagination.value.current,
    size: pagination.value.size,
    total: pagination.value.total,
  };

  let result = await getOrderDetailService(params);
  tableData.value = result.data?.records || [];
  pagination.value.size = result.data?.size || 10;
  pagination.value.current = result.data?.current || 1;
  pagination.value.total = result.data?.total || 0;
};

onMounted(() => {
  fetchUsers();
});
</script>

<style scoped>
/* // 修改容器样式 */
.users-container {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  /* 添加溢出控制 */
  overflow-x: auto;
}

.search-area {
  margin-bottom: 20px;
}

.toolbar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}

/* 美化搜索区域 */
.search-area {
  background: white;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}
</style> 